<template>
  <div class="card">
    <div style="padding:20px; font-size: large ;font-weight: bolder;" v-if="data.user.role === 'USER'">我的申请</div>
    <div style="padding:20px; font-size: large ;font-weight: bolder;" v-if="data.user.role === 'ADMIN'">申请信息</div>
    <div class="card" style="margin-bottom: 5px;">
      <el-input clearable @clear="load" style="width:240px; padding-right:5px" v-model="data.title"
                :prefix-icon="Search" placeholder="请输入申请标题查询"></el-input>
      <el-button type="primary" @click="load">查 询</el-button>
      <el-button type="danger" @click="reset">重 置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px;" v-if="data.user.role === 'USER'">
      <el-button type="primary" @click="handleAdd">新增申请</el-button>
    </div>
    <el-table :data="data.tableData" border style="width: 100%"
              :header-cell-style="{ color:'#333', backgroundColor:'#fff',}" >
      <el-table-column type="index" label="索引" width="60px" />
      <el-table-column prop="title" label="申请标题"  />
      <el-table-column prop="userName" label="申请人" v-if="data.user.role === 'ADMIN'"/>
      <el-table-column prop="content" label="申请内容"  />
      <el-table-column prop="time" label="申请时间"  />
      <el-table-column prop="status" label="审核状态" >
        <template v-slot="scope">
          <el-tag type="warning" v-if="scope.row.status === '待审核'">{{ scope.row.status }}</el-tag>
          <el-tag type="success" v-if="scope.row.status === '审核通过'">{{ scope.row.status }}</el-tag>
          <el-tag type="danger" v-if="scope.row.status === '审核不通过'">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="reason" label="审核理由"  />
      <el-table-column label="操作" width="120">
        <template #default="scope" v-if="data.user.role === 'USER'">
          <el-button :disabled="scope.row.status !== '待审核'" type="primary" icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
          <el-button :disabled="scope.row.status !== '待审核'" type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
        </template>
        <template #default="scope" v-if="data.user.role === 'ADMIN'">
          <el-button :disabled="scope.row.status !== '待审核'" type="primary" @click="handleEdit(scope.row)">审核</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20]"
          :total="data.total"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
      />
    </div>
    <el-dialog title="申请信息" v-model="data.formVisible" width="500" destroy-on-close >
      <el-form ref="formRef" :model="data.form" :rules="data.rules" label-position="right"
               label-width="80px" padding="20px 30px 20px 0">
        <el-form-item prop="title" label="申请标题" v-if="data.user.role === 'USER'">
          <el-input v-model="data.form.title" autocomplete="off" placeholder="请输入申请标题" />
        </el-form-item>
        <el-form-item prop="content" label="申请内容" v-if="data.user.role === 'USER'" >
          <el-input type="textarea" :rows="3" v-model="data.form.content" autocomplete="off" placeholder="请输入申请内容" />
        </el-form-item>
        <el-form-item prop="status" label="审核状态" v-if="data.user.role === 'ADMIN'">
          <el-radio-group v-model="data.form.status">
            <el-radio value="待审核" border>待审核</el-radio>
            <el-radio value="审核通过" border>审核通过</el-radio>
            <el-radio value="审核不通过" border>审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="reason" label="审核理由" style="margin-top:20px" v-if="data.user.role === 'ADMIN' && data.form.status === '审核不通过'">
          <el-input v-model="data.form.reason" autocomplete="off" placeholder="请输入不通过理由" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {Search} from "@element-plus/icons-vue";
import {reactive, ref} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const formRef = ref();

const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || '{}'),
  title:null,
  content:null,
  pageNum:1,
  pageSize:5,
  total:0,
  totalData:[],
  form:{},
  formVisible:false,
  rules:{
    title:[
      {required:true, message:'请填写申请标题', trigger:"blur"}
    ],
    content:[
      {required:true, message:'请填写申请内容', trigger:"blur"}
    ],
  }
})

const load = () => {
  request.get("/apply/selectPage", {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      title: data.title,
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list;
      data.total = res.data?.total;
    }else
      ElMessage(res.msg);
  });
};
load()

const handlePageChange = (newPageNum) => {
  data.pageNum = newPageNum;
  load(); // 重新加载数据
};

const handleSizeChange = (newPageSize) => {
  data.pageSize = newPageSize;
  data.pageNum = 1; // 重置为第一页
  load();
};

const handleAdd = () => {
  data.formVisible = true;
  data.form = {};
}

const reset = () => {
  data.title = null;
  load()
}

const add = () => {
  request.post("/apply/add", data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success("提交成功！等待管理员审核")
      data.formVisible = false;
      load()
    }else{
      ElMessage.error(res.msg)
    }
  })
}

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true;
}

const update = () => {
  request.put("/apply/update", data.form).then((res) => {
    if (res.code === '200') {
      ElMessage.success("操作成功")
      data.formVisible = false;
      load()
    }else{
      ElMessage.erroe(res.msg)
    }
  })
}

const save = () => {
  formRef.value.validate(valid => {
    if (valid) {
      data.form.id ? update() : add()
    }
  })
}

const del = (id) => {
  ElMessageBox.confirm('删除后无法恢复，您确认吗？', '删除确认窗口', {type: 'warning',})
      .then(res => {
        request.delete(`/apply/delete/${id}`).then((res) => {
          if (res.code === '200') {
            ElMessage.success('删除成功');
            load()
          } else {
            ElMessage.error(res.msg);
          }
        })
      }).catch(err => {})
}
</script>